|
Download
FAQ History |
|
API
Search Feedback |
A J2EE Application that Uses the JMS API with an Entity Bean
This section explains how to write, compile, package, deploy, and run a J2EE application that uses the JMS API with an entity bean. The application uses the following components:
The section covers the following topics:
You will find the source files for this section in the directory
<INSTALL>/j2eetutorial14/examples/jms/clientmdbentity/. Path names in this section are relative to this directory.Overview of the Human Resources Application
This application simulates, in a simplified way, the work flow of a company's human resources (HR) department when it processes a new hire. This application also demonstrates how to use the J2EE platform to accomplish a task that many JMS client applications perform.
A JMS client must often wait for several messages from various sources. It then uses the information in all these messages to assemble a message that it then sends to another destination. The common term for this process is joining messages. Such a task must be transactional, with all the receives and the send as a single transaction. If all the messages are not received successfully, the transaction can be rolled back. For a client example that illustrates this task, see A Local Transaction Example.
A message-driven bean can process only one message at a time in a transaction. To provide the ability to join messages, a J2EE application can have the message-driven bean store the interim information in an entity bean. The entity bean can then determine whether all the information has been received; when it has, the entity bean can create and send the message to the other destination. Once it has completed its task, the entity bean can remove itself.
The basic steps of the application are as follows.
- The HR department's application client generates an employee ID for each new hire and then publishes a message containing the new hire's name and employee ID. The client then creates a temporary queue with a message listener that waits for a reply to the message.
- Two message-driven beans process each message: One bean assigns the new hire's office number, and one bean assigns the new hire's equipment. The first bean to process the message creates an entity bean to store the information it has generated. The second bean locates the existing entity bean and adds its information.
- When both the office and the equipment have been assigned, the entity bean sends to the reply queue a message describing the assignments, then removes itself. The application client's message listener retrieves the information.
Figure 21-3 illustrates the structure of this application. An actual HR application would have more components, of course; other beans could set up payroll and benefits records, schedule orientation, and so on.
![]()
Figure 21-3 A J2EE Application: Client to Message-Driven Beans to Entity Bean
Writing the Application Components
Writing the components of the application involves
Coding the Application Client: HumanResourceClient.java
The application client program,
src/HumanResourceClient.java, performs the following steps:
- Uses the JNDI naming context
java:comp/envto look up aConnectionFactoryand a topic- Creates a
TemporaryQueueto receive notification of processing that occurs, based on new-hire events it has published- Creates a
MessageConsumerfor theTemporaryQueue, sets theMessageConsumer's message listener, and starts the connection- Creates a
MessageProducerand aMapMessage- Creates five new employees with randomly generated names, positions, and ID numbers (in sequence) and publishes five messages containing this information
The message listener,
HRListener, waits for messages that contain the assigned office and equipment for each employee. When a message arrives, the message listener displays the information received and checks to see whether all five messages have arrived yet. When they have, the message listener notifies the main program, which then exits.Coding the Message-Driven Beans
This example uses two message-driven beans,
src/ReserveEquipmentMsgBean.javaandsrc/ReserveOfficeMsgBean.java. The beans take the following steps.
- The
ejbCreatemethod gets a handle to the local home interface of the entity bean.- The
onMessagemethod retrieves the information in the message. TheReserveEquipmentMsgBean'sonMessagemethod chooses equipment, based on the new hire's position; theReserveOfficeMsgBean'sonMessagemethod randomly generates an office number.- After a slight delay to simulate real-world processing hitches, the
onMessagemethod calls a helper method,compose.- The
composemethod either creates or finds, by primary key, theSetupOfficeentity bean and uses it to store the equipment or the office information in the database.Coding the Entity Bean
The
SetupOfficebean is an entity bean that uses a local interface. The local interface allows the entity bean and the message-driven beans to be packaged in the same EJB JAR file for maximum efficiency. The entity bean has these components:The local home interface source file is
src/SetupOfficeLocalHome.java. It declares the create method, calledcreateLocalfor a bean that uses a local interface, and one finder method,findByPrimaryKey.The local interface,
src/SetupOfficeLocal.java, declares several business methods that get and manipulate new-hire data.The bean class,
src/SetupOfficeBean.java, implements the business methods and their helper method,checkIfSetupComplete. The bean class also implements the required methodsejbCreateLocal,ejbPostCreateLocal,setEntityContext,unsetEntityContext,ejbRemove,ejbActivate,ejbPassivate,ejbLoad, andejbStore. TheejbFindByPrimaryKeymethod is generated automatically.The only methods called by the message-driven beans are the business methods declared in the local interface, the
findByPrimaryKeymethod, and thecreateLocalmethod. The entity bean uses container-managed persistence, so all database calls are generated automatically.Creating and Packaging the Application
This example uses a connection factory named
jms/TopicConnectionFactoryand a topic namedjms/Topic, both of which you probably created in the previous chapter. If not, see Creating the JMS Administered Objects for the Simple Examples for instructions.Creating and packaging this application involve several steps:
Starting the PointBase Database Server
The PointBase software is included with the J2EE Application Server download bundle. You may also run this example with databases provided by other vendors.
The PointBase server should be started before you start the J2EE Application Server. If the J2EE Application Server is running, stop it as follows:
From the command line prompt, start the PointBase database server.
Compiling the Source Files and Starting the J2EE Application Server
Creating Database Resources
In order to use entity beans that use container-managed persistence with the J2EE Application Server, you must create a JDBC connection pool, a JDBC resource, and a persistence resource. The tutorial provides
asanttargets for all of these. The first two targets are in the file<INSTALL>/j2eetutorial14/examples/common/targets.xml. The last one is in the file<INSTALL>/j2eetutorial14/examples/jms/clientmdbentity/build.xml. Perform the following steps:
- Create a JDBC connection pool named
ejb-tutorial-pool:
asant create-jdbc-connection-pool_common- Create a JDBC resource named
jdbc/ejbTutorialDB:
asant create-jdbc-resource_common- Create a persistence resource named
jdo/cmp-clientmdbentity:
asant create-persistence-resource- Reconfigure the server:
asant reconfig_commonStarting the J2EE Deploytool and Creating the Application
Packaging the Application Client
To package the application client, perform the following steps:
- Choose File
New
Application Client JAR to start the Application Client Wizard.
- In the JAR File Contents screen:
- Verify that Create New AppClient Module in Application is selected and that the application is
ClientMDBEntityApp.- In the AppClient Display Name field, type
HumanResourceClient.- Click the Edit button next to the Contents text area.
- In the dialog box, locate the
build/client/directory. SelectHumanResourceClient.classandHumanResourceClient$HRListener.classfrom the Available Files tree area and click Add, then OK.- In the General screen, select
client.HumanResourceClientin the Main Class combo box.- In the Message Destination References screen, click Add. In the dialog box:
- In the Resource References screen:
- Click Finish.
- Click the Message Destinations tab. In the inspector pane:
Packaging the Message-Driven Beans
Follow these instructions twice, first for the Equipment message-driven bean and then for the Office message-driven bean.
- Choose File
New
Enterprise JavaBean JAR to start the Enterprise Bean Wizard, then click Next.
- In the EJB JAR screen:
- Select Create New JAR Module in Application and verify that the application is
ClientMDBEntityApp. The second time, choose Add to Existing JAR Module.- In the JAR Display Name field, type
EBJAR. (You only do this the first time.)- Click the Edit button next to the Contents text area.
- In the dialog box, locate the
build/eb/directory. SelectReserveEquipmentMsgBean.classfrom the Available Files tree area and click Add, then OK. (The second time, chooseReserveOfficeMsgBean.class.)- In the General screen:
- In the Configuration Options screen, check the Enterprise Bean References and Transaction Management boxes.
- In the Message-Driven Bean Settings screen:
- Click Add in the Activation Configuration Properties area.
- Type
destinationin the Property Name field andPhysicalTopicin the Value field.- Click Add again.
- Type
destinationTypein the Property Name field andjavax.jms.Topicin the Value field.- Choose
javax.jms.Topicfrom the Destination Type menu.- Type
PhysicalTopicin the Destination Name field.- Click Deployment Settings. In the dialog box, type
jmsrain the Resource Adapter field and click OK.- In the Transaction Management screen, choose Container-Managed.
- In the Enterprise Bean References screen, click Add. In the dialog box:
- Type
ejb/local/SetupOfficein the Coded Name field.- Choose Entity from the EJB Type menu.
- Choose Local from the Interfaces menu.
- Type
eb.SetupOfficeLocalHomein the Home Interface field.- Type
eb.SetupOfficeLocalin the Local/Remote Interface field.- Type
SetupOfficein the Enterprise Bean Name field.The entity bean uses local interfaces, so the message-driven beans access the bean through the bean name rather than the JNDI name.
Packaging the Entity Bean
To package the entity bean, perform the following steps:
- Choose File
New
Enterprise JavaBean JAR to start the Enterprise Bean Wizard, then click Next.
- In the EJB JAR screen:
- Choose Add to Existing JAR Module and verify that the module is
EBJAR (ClientMDBEntityApp).- Click the Edit button next to the Contents text area.
- In the dialog box, locate the
build/eb/directory. SelectSetupOfficeBean.class,SetupOfficeLocal.class, andSetupOfficeLocalHome.classfrom the Available Files tree area and click Add, then OK.- In the General screen:
- Choose the Entity radio button.
- From the Enterprise Bean Class menu, choose
eb.SetupOfficeBean.- In the Enterprise Bean Display Name field, type
SetupOffice.- In the Local Interfaces area, choose
eb.SetupOfficeLocalHomefrom the Local Home Interface menu andeb.SetupOfficeLocalfrom the Local Interface menu.- In the Configuration Options screen, check the Resource References and Transaction Management boxes.
- In the Entity Settings screen:
- Select the radio button labeled Container-Managed Persistence (2.0).
- Select the checkboxes next to all six fields in the Fields To Be Persisted area:
employeeId,employeeName,equipmentList,officeNumber,serializedReplyDestination, andreplyCorrelationMsgId.- In the Abstract Schema Name field, type
SetupOfficeSchema.- In the Primary Key Class field, type
java.lang.String.- In the Primary Key Field Name field, select
employeeId.- In the Transaction Management screen, choose Container-Managed.
- In the Resource References screen:
You don't need to specify any message destinations for this bean, because the bean uses a temporary destination for the reply message.
Now, specify the message destinations for the enterprise bean JAR file. Click the EBJAR node, then click the Message Destinations tab. In the inspector pane:
Now, specify the CMP resources for the bean.
Updating the JNDI Names
In the J2EE Application Server, the JNDI name for a message-driven bean is the destination it receives messages from, not the bean name.
Leave the JNDI Name field for the EJB references empty, because you are accessing the entity bean through a local interface.
Verify that the JNDI names for the application components are correct. They should appear as shown in Table 21-6 and Table 21-7.
Table 21-6 Application Pane for ClientMDBEntityApp Component Type Component JNDI Name EJB EquipmentMDB jms/Topic EJB OfficeMDB jms/Topic EJB SetupOffice SetupOffice
Deploying the Application
Saving the Client JAR and Running the Application
- In the deploytool, select the server node.
- Select
ClientMDBEntityAppfrom the list of deployed objects, then click Client Jar.- Choose Browse to navigate to the directory from which you will run the client. Specify the
clientmdbentitydirectory. When you reach the directory, click Select, then click OK. Click OK in the information dialog. You will find a file namedClientMDBEntityAppClient.jarin the specified directory.- To run the client, use the following command:
appclient -client ClientMDBEntityAppClient.jarThe program output in the terminal window looks something like this:
INFO: Binding name:`java:comp/env/jms/NewHireTopic` PUBLISHER: Setting hire ID to 25, name Gertrude Bourbon, position Senior Programmer PUBLISHER: Setting hire ID to 26, name Jack Verdon, position Manager PUBLISHER: Setting hire ID to 27, name Fred Tudor, position Manager PUBLISHER: Setting hire ID to 28, name Fred Martin, position Programmer PUBLISHER: Setting hire ID to 29, name Mary Stuart, position Manager Waiting for 5 message(s) New hire event processed: Employee ID: 25 Name: Gertrude Bourbon Equipment: Laptop Office number: 183 Waiting for 4 message(s) New hire event processed: Employee ID: 26 Name: Jack Verdon Equipment: Pager Office number: 20 Waiting for 3 message(s) New hire event processed: Employee ID: 27 Name: Fred Tudor Equipment: Pager Office number: 51 Waiting for 2 message(s) New hire event processed: Employee ID: 28 Name: Fred Martin Equipment: Desktop System Office number: 141 Waiting for 1 message(s) New hire event processed: Employee ID: 29 Name: Mary Stuart Equipment: Pager Office number: 238The output from the enterprise beans appears in the server log. For each employee, the application first creates the entity bean, then finds it. You may see runtime errors in the server log about transactions and primary keys, and transaction rollbacks may occur. The fact that the client runs correctly in spite of these errors is one of the advantages of container-managed transactions.
Undeploying and Removing the Application
To undeploy and remove the application, perform the following steps:
If you wish, you can manually delete the EAR and client JAR files.
|
Download
FAQ History |
|
API
Search Feedback |
All of the material in The J2EE 1.4 Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.